package com.tao.job.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tao.common.creo.constants.CacheConstants;
import com.tao.common.creo.constants.Constants;
import com.tao.common.redis.service.RedisService;
import com.tao.job.exam.Exam;
import com.tao.job.mapper.ExamMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ExamXxlJob {

    @Autowired
    ExamMapper examMapper;
    @Autowired
    RedisService redisService;
    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler() {
        // 未完赛竞赛列表
        List<Exam> unFinishList = examMapper.selectList(
                new LambdaQueryWrapper<Exam>()
                        .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                        .gt(Exam::getEndTime, LocalDateTime.now())
                        .eq(Exam::getStatus, Constants.TRUE)
                        .orderByDesc(Exam::getCreateTime)
        );
        refreshCache(getUnFinishExamListKey(), unFinishList);

        // 历史竞赛列表
        List<Exam> historyExamList = examMapper.selectList(
                new LambdaQueryWrapper<Exam>()
                        .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                        .le(Exam::getEndTime, LocalDateTime.now())
                        .eq(Exam::getStatus, Constants.TRUE)
                        .orderByDesc(Exam::getCreateTime)
        );
        refreshCache(getHistoryListKey(), historyExamList);
    }

    private String getUnFinishExamListKey() {
        return CacheConstants.EXAM_UNFINISHED_LIST;
    }

    private String getHistoryListKey() {
        return CacheConstants.EXAM_HISTORY_LIST;
    }

    public void refreshCache(String examListKey, List<Exam> examList) {
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }

        redisService.multiSet(examMap); // 刷新详情缓存
        redisService.deleteObject(examListKey); // 删除旧的列表缓存
        redisService.rightPushAll(examListKey, examIdList); // 刷新列表缓存
    }
    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

}
